import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Statistic, Typography, Table, Tag } from 'antd';
import { ShoppingOutlined, DollarOutlined, UserOutlined, TruckOutlined } from '@ant-design/icons';
import { Order, Product } from '../../types';
import { Storage, STORAGE_KEYS } from '../../utils/storage';
import { mockProducts } from '../../services/mockData';

const { Title } = Typography;

const Dashboard: React.FC = () => {
  const [orders, setOrders] = useState<Order[]>([]);
  const [products, setProducts] = useState<Product[]>([]);

  useEffect(() => {
    const orderData = Storage.get<Order[]>(STORAGE_KEYS.ORDERS) || [];
    setOrders(orderData);
    setProducts(mockProducts);
  }, []);

  const getStatusInfo = (status: Order['status']) => {
    const statusMap = {
      pending: { text: '待付款', color: 'orange' },
      paid: { text: '已付款', color: 'blue' },
      shipped: { text: '已发货', color: 'cyan' },
      delivered: { text: '已送达', color: 'green' },
      cancelled: { text: '已取消', color: 'red' }
    };
    return statusMap[status];
  };

  // 统计数据
  const totalOrders = orders.length;
  const totalRevenue = orders
    .filter(order => order.status !== 'cancelled')
    .reduce((sum, order) => sum + order.totalAmount, 0);
  const pendingOrders = orders.filter(order => order.status === 'pending').length;
  const shippingOrders = orders.filter(order => order.status === 'shipped').length;

  // 最近订单表格列
  const orderColumns = [
    {
      title: '订单号',
      dataIndex: 'id',
      key: 'id',
      render: (id: string) => id.slice(0, 8) + '...'
    },
    {
      title: '商品数量',
      dataIndex: 'items',
      key: 'items',
      render: (items: any[]) => `${items.length} 件`
    },
    {
      title: '订单金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount: number) => `¥${amount.toFixed(2)}`
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: Order['status']) => {
        const statusInfo = getStatusInfo(status);
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
      }
    },
    {
      title: '下单时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleDateString()
    }
  ];

  return (
    <div>
      <Title level={2}>仪表盘</Title>
      
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总订单数"
              value={totalOrders}
              prefix={<ShoppingOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总营收"
              value={totalRevenue}
              precision={2}
              prefix={<DollarOutlined />}
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="待付款订单"
              value={pendingOrders}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="待发货订单"
              value={shippingOrders}
              prefix={<TruckOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={16}>
        {/* 最近订单 */}
        <Col xs={24} lg={16}>
          <Card title="最近订单" style={{ marginBottom: 16 }}>
            <Table
              columns={orderColumns}
              dataSource={orders.slice(0, 10)}
              rowKey="id"
              pagination={false}
              size="small"
            />
          </Card>
        </Col>

        {/* 热门商品 */}
        <Col xs={24} lg={8}>
          <Card title="热门商品" style={{ marginBottom: 16 }}>
            {products
              .filter(p => p.isHot)
              .slice(0, 5)
              .map(product => (
                <div key={product.id} style={{ 
                  display: 'flex', 
                  alignItems: 'center', 
                  marginBottom: 16,
                  padding: 8,
                  border: '1px solid #f0f0f0',
                  borderRadius: 4
                }}>
                  <img
                    src={product.image}
                    alt={product.name}
                    style={{ width: 40, height: 40, objectFit: 'cover', marginRight: 12 }}
                  />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: '14px', fontWeight: 500 }}>
                      {product.name}
                    </div>
                    <div style={{ fontSize: '12px', color: '#999' }}>
                      销量: {product.sales}
                    </div>
                  </div>
                  <div style={{ color: '#f50', fontWeight: 'bold' }}>
                    ¥{product.price}
                  </div>
                </div>
              ))}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;
